/**
 * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
 * For licensing, see LICENSE.md.
 */

/**
 * @module heading/headingui
 */

import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
import Model from '@ckeditor/ckeditor5-ui/src/model';

import { createDropdown, addListToDropdown } from '@ckeditor/ckeditor5-ui/src/dropdown/utils';
import { getLocalizedOptions } from './utils';

import Collection from '@ckeditor/ckeditor5-utils/src/collection';
import './../theme/lineHeight.css';
/**
 * The headings UI feature. It introduces the `headings` dropdown.
 *
 * @extends module:core/plugin~Plugin
 */
const LINE_HEIGHT = 'lineHeight';
export default class LineHeightUi extends Plugin {
	/**
	 * @inheritDoc
	 */
	init() {
		const editor = this.editor;
		const t = editor.t;
		const options = getLocalizedOptions( editor );
		const defaultTitle = t( 'line height' );
		const dropdownTooltip = t( 'line height' );

		// Register UI component.
		editor.ui.componentFactory.add( 'lineHeight', locale => {
			const titles = {};
			const command = editor.commands.get( 'lineHeight' );

			const dropdownView = createDropdown( locale );
			addListToDropdown( dropdownView, _prepareLineHeightOptions( options, command,titles) );

			dropdownView.buttonView.set( {
				isOn: false,
				withText: true,
				tooltip: dropdownTooltip
			} );

			dropdownView.extendTemplate( {
				attributes: {
					class: 'ck-line-height-dropdown'
				}
			} );


			dropdownView.bind( 'isEnabled' ).to( command );

			dropdownView.buttonView.bind( 'label' ).to( command, 'value',( value, para ) => {
				const whichModel = value || para ;
				// If none of the commands is active, display default title.
				return titles[ whichModel ] ? titles[ whichModel ] : defaultTitle;
			} );

			// Execute command when an item from the dropdown is selected.
			this.listenTo( dropdownView, 'execute', evt => {
				editor.execute( evt.source.commandName, { value: evt.source.commandParam } );
				editor.editing.view.focus();
			} );

			return dropdownView;
		} );
	}
}

function _prepareLineHeightOptions( options, command,titles) {
	const itemDefinitions = new Collection();

	for ( const option of options ) {
		const def = {
			type: 'button',
			model: new Model( {
				commandName: LINE_HEIGHT,
				commandParam: option.title,
				label: option.title,
				class: option.class,
				withText: true
			} )
		};
		def.model.bind( 'isOn' ).to( command, 'value', value => value === option.title );
		// Add the option to the collection.
		itemDefinitions.add( def );
		titles[ option.model ] = option.title;
	}

	return itemDefinitions;
}
